{% extends 'base.html' %}
{% block title %}原始数据{% endblock %}
{% block nav %}原始数据{% endblock %}
{% block css %}
    <link href="../static/assets/css/raw_data.css" rel="stylesheet"/>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
{% endblock %}
{% block Sidebar %}
    <div class="sidebar" data-color="orange">
        <div class="logo">
            <a href="#" class="simple-text logo-mini">
                <img src="../static/assets/img/taobaologo.png" alt="#"/>
            </a>
            <a href="#" class="simple-text logo-normal">
                电商平台用户行为预测系统
            </a>
        </div>
        <div class="sidebar-wrapper">
            <ul class="nav">
                <li>
                    <a href="{{ url_for('ec.index') }}">
                        <i class="now-ui-icons design_app"></i>
                        <p>仪表盘</p>
                    </a>
                </li>
                <li class="active">
                    <a href="{{ url_for('ec.raw_data') }}">
                        <i class="now-ui-icons business_chart-pie-36"></i>
                        <p>原始数据</p>
                    </a>
                </li>
                <li>
                    <a href="{{ url_for('ec.visual2') }}">
                        <i class="now-ui-icons education_atom"></i>
                        <p>预测与推荐</p>
                    </a>
                </li>
                <li>
                    <a href="{{ url_for('ec.visual') }}">
                        <i class="now-ui-icons files_single-copy-04"></i>
                        <p>操作日志</p>
                    </a>
                </li>
                <li>
                    <a href="{{ url_for('ec.user') }}">
                        <i class="now-ui-icons users_single-02"></i>
                        <p>个人中心</p>
                    </a>
                </li>
            </ul>
        </div>
    </div>
{% endblock %}

{% block content %}
    <div class="panel-header panel-header-sm" style="background: linear-gradient(135deg, #F5F5F5 0%, #1c84fc 100%);"></div>
    <div class="content">
        <!-- 数据概览卡片 -->
        <div class="row">
            <div class="col-md-3">
                <div class="card card-stats">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-5">
                                <div class="icon-big text-center icon-warning">
                                    <i class="now-ui-icons users_single-02 text-primary"></i>
                                </div>
                            </div>
                            <div class="col-7">
                                <div class="numbers">
                                    <p class="card-category">用户数量</p>
                                    <h4 class="card-title">{{ user_count }}</h4>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card card-stats">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-5">
                                <div class="icon-big text-center icon-warning">
                                    <i class="now-ui-icons shopping_tag-content text-success"></i>
                                </div>
                            </div>
                            <div class="col-7">
                                <div class="numbers">
                                    <p class="card-category">商品数量</p>
                                    <h4 class="card-title">{{ item_count }}</h4>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card card-stats">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-5">
                                <div class="icon-big text-center icon-warning">
                                    <i class="now-ui-icons shopping_shop text-info"></i>
                                </div>
                            </div>
                            <div class="col-7">
                                <div class="numbers">
                                    <p class="card-category">类目数量</p>
                                    <h4 class="card-title">{{ category_count }}</h4>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card card-stats">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-5">
                                <div class="icon-big text-center icon-warning">
                                    <i class="now-ui-icons ui-2_settings-90 text-danger"></i>
                                </div>
                            </div>
                            <div class="col-7">
                                <div class="numbers">
                                    <p class="card-category">行为记录</p>
                                    <h4 class="card-title">{{ total_records }}</h4>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 数据导入卡片 -->
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h5 class="card-category">数据管理</h5>
                                <h4 class="card-title">数据导入</h4>
                            </div>
                            <div class="btn-group">
                                <button class="btn btn-sm btn-info" id="exportDataBtn">
                                    <i class="now-ui-icons arrows-1_cloud-download-93"></i> 导出数据
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <form id="uploadForm" class="dropzone" action="{{ url_for('ec.upload_file') }}" method="POST"
                              enctype="multipart/form-data">
                            <div class="row">
                                <div class="col-md-8">
                                    <div class="custom-file">
                                        <input type="file" class="custom-file-input" id="fileInput" name="file"
                                               accept=".csv">
                                        <label class="custom-file-label" for="fileInput">选择CSV文件</label>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <button type="submit" class="btn btn-primary btn-block">
                                        <i class="now-ui-icons arrows-1_cloud-upload-94"></i> 上传
                                    </button>
                                </div>
                            </div>
                            <div class="row mt-3">
                                <div class="col-md-12">
                                    <div class="progress" id="uploadProgress" style="display: none;">
                                        <div class="progress-bar progress-bar-striped progress-bar-animated"
                                             role="progressbar" style="width: 0%"></div>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- 数据展示卡片 -->
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h5 class="card-category">数据分析</h5>
                                <h4 class="card-title">原始数据</h4>
                            </div>
                            <div class="btn-group">
                                <button class="btn btn-sm btn-info" id="filterBtn">
                                    <i class="now-ui-icons ui-1_zoom-bold"></i> 筛选
                                </button>
                                <button class="btn btn-sm btn-success" id="refreshBtn">
                                    <i class="now-ui-icons arrows-1_refresh-69"></i> 刷新
                                </button>
                                <button class="btn btn-sm btn-primary" id="toggleDataBtn">
                                    <i class="now-ui-icons ui-1_zoom-bold"></i> 查看数据
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <!-- 筛选表单 -->
                        <div class="row mb-3" id="filterForm" style="display: none;">
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label>用户ID</label>
                                    <input type="text" class="form-control" id="filterUserId" placeholder="输入用户ID">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label>商品ID</label>
                                    <input type="text" class="form-control" id="filterItemId" placeholder="输入商品ID">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label>行为类型</label>
                                    <select class="form-control" id="filterBehaviorType">
                                        <option value="">全部</option>
                                        <option value="pv">点击</option>
                                        <option value="cart">加购</option>
                                        <option value="fav">收藏</option>
                                        <option value="buy">购买</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label>&nbsp;</label>
                                    <button class="btn btn-primary btn-block" id="applyFilterBtn">
                                        <i class="now-ui-icons ui-1_check"></i> 应用
                                    </button>
                                </div>
                            </div>
                        </div>

                        <!-- 数据表格 -->
                        <div class="table-responsive" id="dataTableSection" style="display:none;">
                            <table class="table table-hover" id="dataTable">
                                <thead class="text-primary">
                                <tr>
                                    <th>用户ID <i class="fas fa-sort"></i></th>
                                    <th>商品ID <i class="fas fa-sort"></i></th>
                                    <th>商品类目ID <i class="fas fa-sort"></i></th>
                                    <th>行为类型 <i class="fas fa-sort"></i></th>
                                    <th>时间戳 <i class="fas fa-sort"></i></th>
                                    <th>操作</th>
                                </tr>
                                </thead>
                                <tbody>
                                {% for row in raw_data %}
                                    <tr>
                                        <td>{{ row.user_id }}</td>
                                        <td>{{ row.item_id }}</td>
                                        <td>{{ row.category_id }}</td>
                                        <td>
                                            <span class="badge badge-{{ 'primary' if row.behavior_type == 'pv' else
                                                  'success' if row.behavior_type == 'buy' else
                                                    'warning' if row.behavior_type == 'cart' else 'info' }}">
                                                {{ '点击' if row.behavior_type == 'pv' else
                                                   '购买' if row.behavior_type == 'buy' else
                                                        '加购' if row.behavior_type == 'cart' else '收藏' }}
                                            </span>
                                        </td>
                                        <td>{{ row.timestamp.strftime('%Y-%m-%d %H:%M:%S') }}</td>
                                        <td>
                                            <button class="btn btn-sm btn-outline-info view-details"
                                                    data-id="{{ row.id }}">
                                                <i class="now-ui-icons ui-1_zoom-bold"></i>
                                            </button>
                                        </td>
                                    </tr>
                                {% endfor %}
                                </tbody>
                            </table>

                            <!-- 分页导航栏 -->
                            <div class="pagination-container d-flex justify-content-between align-items-center">
                                <div>
                                    <span class="page-info">显示 {{ pagination.first }} 到 {{ pagination.last }} 条，共 {{ pagination.total }} 条记录</span>
                                </div>
                                <div>
                                    <!-- 修改分页导航栏部分 -->
                                    <nav aria-label="Page navigation">
                                        <ul class="pagination pagination-primary">
                                            <li class="page-item {% if not pagination.has_prev %}disabled{% endif %}">
                                                <a class="page-link"
                                                   href="?page=1{% if request.args.get('user_id') %}&user_id={{ request.args.get('user_id') }}{% endif %}{% if request.args.get('item_id') %}&item_id={{ request.args.get('item_id') }}{% endif %}{% if request.args.get('behavior_type') %}&behavior_type={{ request.args.get('behavior_type') }}{% endif %}"
                                                   aria-label="First">
                                                    <span aria-hidden="true">&laquo;&laquo;</span>
                                                </a>
                                            </li>
                                            <li class="page-item {% if not pagination.has_prev %}disabled{% endif %}">
                                                <a class="page-link" href="?page=


                                                        {{ pagination.prev_num }}{% if request.args.get('user_id') %}&user_id={{ request.args.get('user_id') }}{% endif %}{% if request.args.get('item_id') %}&item_id={{ request.args.get('item_id') }}{% endif %}{% if request.args.get('behavior_type') %}&behavior_type={{ request.args.get('behavior_type') }}{% endif %}"
                                                   aria-label="Previous">
                                                    <span aria-hidden="true">&laquo;</span>
                                                </a>
                                            </li>
                                            {% for p in pagination.iter_pages() %}
                                                <li class="page-item {% if p == pagination.page %}active{% endif %}">
                                                    <a class="page-link" href="?page=


                                                            {{ p }}{% if request.args.get('user_id') %}&user_id={{ request.args.get('user_id') }}{% endif %}{% if request.args.get('item_id') %}&item_id={{ request.args.get('item_id') }}{% endif %}{% if request.args.get('behavior_type') %}&behavior_type={{ request.args.get('behavior_type') }}{% endif %}">{{ p }}</a>
                                                </li>
                                            {% endfor %}
                                            <li class="page-item {% if not pagination.has_next %}disabled{% endif %}">
                                                <a class="page-link" href="?page=


                                                        {{ pagination.next_num }}{% if request.args.get('user_id') %}&user_id={{ request.args.get('user_id') }}{% endif %}{% if request.args.get('item_id') %}&item_id={{ request.args.get('item_id') }}{% endif %}{% if request.args.get('behavior_type') %}&behavior_type={{ request.args.get('behavior_type') }}{% endif %}"
                                                   aria-label="Next">
                                                    <span aria-hidden="true">&raquo;</span>
                                                </a>
                                            </li>
                                            <li class="page-item {% if not pagination.has_next %}disabled{% endif %}">
                                                <a class="page-link" href="?page=


                                                        {{ pagination.pages }}{% if request.args.get('user_id') %}&user_id={{ request.args.get('user_id') }}{% endif %}{% if request.args.get('item_id') %}&item_id={{ request.args.get('item_id') }}{% endif %}{% if request.args.get('behavior_type') %}&behavior_type={{ request.args.get('behavior_type') }}{% endif %}"
                                                   aria-label="Last">
                                                    <span aria-hidden="true">&raquo;&raquo;</span>
                                                </a>
                                            </li>
                                        </ul>
                                    </nav>
                                </div>
                                <div>
                                    <div class="input-group">
                                        <input type="number" id="pageInput" class="form-control" min="1"
                                               max="{{ pagination.pages }}" placeholder="页码">
                                        <div class="input-group-append">
                                            <button class="btn btn-primary" onclick="goToCustomPage()">跳转</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 数据清洗卡片 -->
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h5 class="card-category">数据质量</h5>
                                <h4 class="card-title">数据清洗</h4>
                            </div>
                            <div>
                                <button class="btn btn-sm btn-warning" id="cleanDataBtn">
                                    <i class="now-ui-icons design_scissors"></i> 清洗数据
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="alert alert-info">
                                    <div class="container">
                                        <div class="alert-icon">
                                            <i class="now-ui-icons travel_info"></i>
                                        </div>
                                        <strong>数据清洗说明</strong>
                                        <p>数据清洗将自动处理以下问题：</p>
                                        <ul>
                                            <li>去除行为类型为空的记录</li>
                                            <li>格式化时间戳</li>
                                            <li>检查数据完整性</li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="table-responsive" id="cleanedDataSection" style="display:none;">
                                    <table class="table table-hover">
                                        <thead>
                                        <tr class="text-primary">
                                            <th>用户ID</th>
                                            <th>商品ID</th>
                                            <th>商品类目ID</th>
                                            <th>行为类型</th>
                                            <th>时间戳</th>
                                        </tr>
                                        </thead>
                                        <tbody id="cleanedDataTable">
                                        <!-- 清洗后的数据将动态插入到这里 -->
                                        </tbody>
                                    </table>
                                </div>
                                <div id="cleaningStatus" class="text-center" style="display:none;">
                                    <div class="spinner-border text-primary" role="status">
                                        <span class="sr-only">正在清洗数据...</span>
                                    </div>
                                    <p class="mt-2">正在清洗数据，请稍候...</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 详情模态框 -->
    <div class="modal fade" id="detailModal" tabindex="-1" role="dialog" aria-labelledby="detailModalLabel"
         aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="detailModalLabel">行为详情</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body" id="detailModalContent">
                    <!-- 详情内容将通过AJAX加载 -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block js %}
    <script src="../static/assets/js/raw_data.js"></script>
    <script>
        // 跳转到指定页码
        function goToPage(page) {
            if (page >= 1 && page <= {{ pagination.pages }}) {
                // 获取当前筛选条件
                const userId = document.getElementById('filterUserId').value;
                const itemId = document.getElementById('filterItemId').value;
                const behaviorType = document.getElementById('filterBehaviorType').value;

                // 构建URL
                let url = "{{ url_for('ec.raw_data') }}?page=" + page;
                if (userId) url += "&user_id=" + userId;
                if (itemId) url += "&item_id=" + itemId;
                if (behaviorType) url += "&behavior_type=" + behaviorType;

                window.location.href = url;
            }
        }

        // 跳转到用户输入的页码
        function goToCustomPage() {
            const pageInput = document.getElementById('pageInput');
            const page = parseInt(pageInput.value);

            if (page >= 1 && page <= {{ pagination.pages }}) {
                goToPage(page);
            } else {
                alert('请输入有效的页码（1 到 {{ pagination.pages }}）');
            }
        }

        // 监听回车键
        document.getElementById('pageInput').addEventListener('keyup', function (event) {
            if (event.key === 'Enter') {
                goToCustomPage();
            }
        });

        // 显示/隐藏数据表格
        document.getElementById('toggleDataBtn').addEventListener('click', function () {
            const section = document.getElementById('dataTableSection');
            if (section.style.display === 'none') {
                section.style.display = 'block';
                this.innerHTML = '<i class="now-ui-icons ui-1_simple-remove"></i> 隐藏数据';
            } else {
                section.style.display = 'none';
                this.innerHTML = '<i class="now-ui-icons ui-1_zoom-bold"></i> 查看数据';
            }
        });

        // 显示/隐藏筛选表单
        document.getElementById('filterBtn').addEventListener('click', function () {
            const form = document.getElementById('filterForm');
            if (form.style.display === 'none') {
                form.style.display = 'block';
                this.innerHTML = '<i class="now-ui-icons ui-1_simple-remove"></i> 隐藏筛选';
            } else {
                form.style.display = 'none';
                this.innerHTML = '<i class="now-ui-icons ui-1_zoom-bold"></i> 筛选';
            }
        });

        // 应用筛选
        document.getElementById('applyFilterBtn').addEventListener('click', function () {
            goToPage(1); // 应用筛选后回到第一页
        });

        // 刷新页面
        document.getElementById('refreshBtn').addEventListener('click', function () {
            window.location.reload();
        });

        // 导出数据
        document.getElementById('exportDataBtn').addEventListener('click', function () {
            // 获取当前筛选条件
            const userId = document.getElementById('filterUserId').value;
            const itemId = document.getElementById('filterItemId').value;
            const behaviorType = document.getElementById('filterBehaviorType').value;

            // 构建URL
            let url = "{{ url_for('ec.download_logs') }}";
            let params = [];
            if (userId) params.push("user_id=" + userId);
            if (itemId) params.push("item_id=" + itemId);
            if (behaviorType) params.push("behavior_type=" + behaviorType);

            if (params.length > 0) {
                url += "?" + params.join("&");
            }

            window.location.href = url;
        });

        // 查看详情
        document.querySelectorAll('.view-details').forEach(button => {
            button.addEventListener('click', function () {
                const recordId = this.getAttribute('data-id');
                fetch('/get_record_details?id=' + recordId)
                    .then(response => response.json())
                    .then(data => {
                        document.getElementById('detailModalContent').innerHTML = `
                            <div class="row">
                                <div class="col-md-6">
                                    <p><strong>用户ID:</strong> ${data.user_id}</p>
                                    <p><strong>商品ID:</strong> ${data.item_id}</p>
                                    <p><strong>商品类目ID:</strong> ${data.category_id}</p>
                                </div>
                                <div class="col-md-6">
                                    <p><strong>行为类型:</strong> <span class="badge badge-${data.behavior_type === 'pv' ? 'primary' :
                            data.behavior_type === 'buy' ? 'success' :
                                data.behavior_type === 'cart' ? 'warning' : 'info'}">
                                        ${data.behavior_type === 'pv' ? '点击' :
                            data.behavior_type === 'buy' ? '购买' :
                                data.behavior_type === 'cart' ? '加购' : '收藏'}
                                    </span></p>
                                    <p><strong>时间戳:</strong> ${data.timestamp}</p>
                                    <p><strong>记录ID:</strong> ${data.id}</p>
                                </div>
                            </div>
                            <div class="row mt-3">
                                <div class="col-md-12">
                                    <div class="card">
                                        <div class="card-header">
                                            <h5>用户行为分析</h5>
                                        </div>
                                        <div class="card-body">
                                            <canvas id="userBehaviorChart"></canvas>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        `;

                        // 初始化图表
                        initializeUserBehaviorChart(data.user_id);

                        $('#detailModal').modal('show');
                    });
            });
        });

        function initializeUserBehaviorChart(userId) {
            // 这里可以添加获取用户行为数据并绘制图表的代码
            console.log("Initializing chart for user: " + userId);
        }
    </script>
{% endblock %}